/*
 * Copyright (C) 2015 EasyFonts
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.hookedonplay.decoviewsample;

import com.hookedonplay.decoviewlib.LogUtil;
import ohos.agp.text.Font;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;

import java.io.*;
import java.util.Optional;

public class FontSourceProcessor {
    private static final String TAG = "FontSourceProcessor";

    private static final int BUFFER_LENGTH = 8192;
    public static final int DEFAULT_ERROR = -1;

    public static String getPathById(Context context, int id) {
        String path = "";
        if (context == null) {
            return path;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            return path;
        }
        try {
            path = manager.getMediaPath(id);
        } catch (IOException | NotExistException | WrongTypeException e) {
            return path;
        }
        return path;
    }

    /**
     * parse raw font resource path
     *
     * @param id
     * @param context
     * @return Font
     */
    public static Font process(int id, Context context) {
        Font sResFont;
        String path = getPathById(context, id);
        File file = new File(context.getDataDir(), System.currentTimeMillis() + ".ttf");
        try (OutputStream outputStream = new FileOutputStream(file);
             InputStream inputStream = context.getResourceManager().getRawFileEntry(path).openRawFile()) {
            byte[] buffer = new byte[BUFFER_LENGTH];
            int bytesRead = inputStream.read(buffer, 0, BUFFER_LENGTH);
            while (bytesRead != DEFAULT_ERROR) {
                outputStream.write(buffer, 0, bytesRead);
                bytesRead = inputStream.read(buffer, 0, BUFFER_LENGTH);
            }
        } catch (FileNotFoundException exception) {
            LogUtil.error(TAG, "Process FileNotFoundException");

        } catch (IOException exception) {
            LogUtil.error(TAG, "Process IOException");
        }

        sResFont = Optional.of(new Font.Builder(file).build()).get();
        file.delete();

        return sResFont;
    }
}